package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.system.domain.SoftwareUser;
import com.ecnu.system.domain.dto.SoftwareUserDTO;
import com.ecnu.system.mapper.SoftwareUserMapper;
import com.ecnu.system.service.ISoftwareUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-10-29
 */
@Service
public class SoftwareUserServiceImpl extends ServiceImpl<SoftwareUserMapper, SoftwareUser> implements ISoftwareUserService {

    @Autowired
    private SoftwareUserMapper softwareUserMapper;
    @Override
    public AjaxResult grant( SoftwareUserDTO dto, LoginUser loginUser) {
        try {
            LambdaQueryWrapper<SoftwareUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SoftwareUser::getSoftwareId, dto.getSoftwareId())
                    .eq(SoftwareUser::getUserId, loginUser.getUserId())
                    .eq(SoftwareUser::getDelFlag, "0");
            Long aLong = softwareUserMapper.selectCount(wrapper);
            if (aLong > 0) {
                return AjaxResult.success("您已通过授权");
            }
            SoftwareUser softwareUser = new SoftwareUser();
            softwareUser.setSoftwareId(dto.getSoftwareId());
            softwareUser.setUserId(loginUser.getUserId());
            int insert = softwareUserMapper.insert(softwareUser);
            return AjaxResult.success("授权成功");
        }catch (Exception e){
            log.error("****工具授权异常：" + e.getMessage());
            return AjaxResult.error("工具授权异常，请联系管理员处理");
        }
    }
}
